const cloud = require('wx-server-sdk')

cloud.init()

const SUCCESS = 0;
const BAD_PARAM = -1;
const NOT_FOUND = -2;

/// (isbn: IsbnString) => (code: StatusCode, result?: Article)
exports.main = async (event) => {
  const isbn = event.isbn;
  
  if (isbn == null) {
    return {
      code: BAD_PARAM
    };
  }

  const db = cloud.database();
  try {
    const book = await db.collection('books').where({
      isbn: db.command.eq(isbn)
    }).get();

    if (book.data.length < 1) {
      return {
        code: NOT_FOUND
      };
    } else {
      book.data = book.data[0];
      return {
        code: SUCCESS,
        result: book
      };
    }
  } catch (e) {
    return {
      code: NOT_FOUND
    };
  }
}
